package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.util.ModifyUtil;
import com.softer.wxzj.common.util.ShiroUserUtil;
import com.softer.wxzj.common.util.UUIDUtil;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.BaseCellInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * BaseCellInfoServiceImpl class
 *
 * @author zcz
 * @date 2019/1/16
 */
@Service
public class BaseCellInfoServiceImpl implements BaseCellInfoService {
    @Autowired
    private ModifyUtil<BaseCellInfo> modifyUtil;
    @Autowired
    BaseBuildInfoMapper baseBuildInfoMapper;
    @Autowired
    BaseCellInfoMapper baseCellInfoMapper;
    @Autowired
    BaseHouseInfoMapper baseHouseInfoMapper;
    @Autowired
    DicContentMapper dicContentMapper;
    @Autowired
    BaseRegionInfoMapper baseRegionInfoMapper;
    @Autowired
    BaseSubRegionInfoMapper baseSubRegionInfoMapper;
    @Autowired
    ZoneCodeMapper zoneCodeMapper;
    @Autowired
    private BaseModifyDetailMapper baseModifyDetailMapper;
    @Autowired
    private BaseModifyReqMapper baseModifyReqMapper;
    @Autowired
    private BaseCellInfoService baseCellInfoService;
    @Autowired
    private ExpProjectReqDetailMapper expProjectReqDetailMapper;
    @Autowired
    private FlowInstanceMapper flowInstanceMapper;

    @Override
    public CommonResult insertOrUpdate(List<BaseCellInfo> list) {

        if (list.isEmpty()) {
            return CommonResult.ResponseResult(0, "请添加数据再保存");
        }
        int co = flowInstanceMapper.getCountByBusinessIdByType(list.get(0).getBuildNo(), "base_cell_info_update");
        if (co > 0) {
            return CommonResult.ResponseResult(0, "该自然幢正在进行单元(房屋结构)变更(无法修改（新增）");
        }
        co = baseModifyReqMapper.selectCountByBusinessIdNotFlow(list.get(0).getBuildNo());
        if (co > 0) {
            return CommonResult.ResponseResult(0, "该自然幢单元(房屋结构)变更保存中无法修改（新增）");
        }
        int check = checkUpdate(list);
        if (NumberEnum.MINUS_ONE.getNum() == check) {
            return new CommonResult(ShiroResultEnum.FAIL.getCode(), "参数不合法！请检查开始楼层、结束楼层、户数信息！");
        }
        String sortType = baseBuildInfoMapper.getSortTypeById(list.get(0).getBuildNo());
        BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(list.get(0).getBuildNo());
        String subRegionName = "";
        if (null != baseBuildInfo && null != baseBuildInfo.getSubRegionNo()) {
            BaseSubRegionInfo info = baseSubRegionInfoMapper.getInfo(baseBuildInfo.getSubRegionNo());
            if (null != info && null != info.getSubRegionName()) {
                subRegionName = info.getSubRegionName();
            }
        }
        BaseRegionInfo baseRegionInfo = baseRegionInfoMapper.getInfo(baseBuildInfo.getRegionNo());
        String zoneName = zoneCodeMapper.getZoneName(StringUtils.substring
                (baseRegionInfo.getZoneCode(), 0, 4));
        //房屋坐落 区+小区名+ 分区名 +自然幢名+单元名+房间名
        String houseSite = zoneName + baseRegionInfo.getRegionName() + subRegionName + baseBuildInfo.getBuildName();
        int num = buildHouse(list, sortType, houseSite, baseBuildInfo);
        return CommonResult.ResponseResult(num);
    }


    /**
     * 检出变更条件
     *
     * @param list
     * @return
     */
    private int checkUpdate(List<BaseCellInfo> list) {
        int num = NumberEnum.ZERO.getNum();
        for (BaseCellInfo baseCellInfo : list) {
            if (StringUtils.isNotBlank(baseCellInfo.getId())) {
                BaseCellInfo info = baseCellInfoMapper.getInfo(baseCellInfo.getId());
                if (null != info) {
                    if (Integer.parseInt(info.getStartFloor()) < Integer.parseInt(baseCellInfo.getStartFloor())
                            || Integer.parseInt(info.getEndFloor()) > Integer.parseInt(baseCellInfo.getEndFloor())
                            || Integer.parseInt(info.getHouseNum()) > Integer.parseInt(baseCellInfo.getHouseNum())) {
                        return NumberEnum.MINUS_ONE.getNum();
                    }
                }
            }
        }
        return num;
    }

    /**
     * 创建单元
     *
     * @param baseCellInfo
     * @param cellNo
     * @return
     */
    public BaseCellInfo buildCell(BaseCellInfo baseCellInfo, int cellNo) {
        int num = NumberEnum.ONE.getNum();
        // 判断是否有id
        if (StringUtils.isNotBlank(baseCellInfo.getId())) {
            //查询信息
            //BaseCellInfo info = baseCellInfoMapper.getInfoById(baseCellInfo.getId());
            BaseCellInfo info = baseCellInfoMapper.getInfo(baseCellInfo.getId());
            if (null != info) {
                if (info.getStartFloor().equals(baseCellInfo.getStartFloor())
                        && info.getEndFloor().equals(baseCellInfo.getEndFloor())
                        && info.getHouseNum().equals(baseCellInfo.getHouseNum())) {
                    num = NumberEnum.ZERO.getNum();
                }
            } else {
                num = NumberEnum.ZERO.getNum();
            }
        } else {
            baseCellInfo.setId(UUIDUtil.getUUID());
            //查看变更表有没有未审核的数据

            baseCellInfo.setCellNo(String.format("%04d", cellNo));
            //楼层数 = 终止楼层 - 开始楼层 + 1
            baseCellInfo.setFloorNum(String.valueOf(Integer.parseInt(baseCellInfo.getEndFloor()) - Integer.parseInt(baseCellInfo.getStartFloor()) + 1));
            baseCellInfo.setState(String.valueOf(NumberEnum.ONE.getNum()));
            baseCellInfo.setCreater(ShiroUserUtil.getUserName());
        }
        baseCellInfoMapper.insertOrUpdate(baseCellInfo);
        //查询是否有房间   没有房间则返回baseCellInfo
        int count = baseHouseInfoMapper.getHouseCountByCellNo(baseCellInfo.getId());
        if (NumberEnum.ZERO.getNum() == num && count > 0) {
            baseCellInfo = null;
        }
        return baseCellInfo;
    }

    /**
     * 获取单元编号
     *
     * @param buildId 自然幢ID
     * @return 单元编号
     */
    public int getCellNo(String buildId, int cellNo) {
        String newCellNo = baseModifyReqMapper.selectCellNo(buildId);
        if (StringUtils.isNotBlank(newCellNo)) {
            cellNo = Integer.parseInt(newCellNo.substring(2)) + 1;
        } else {
            cellNo = cellNo + 1;
        }
        return cellNo;
    }

    /**
     * 生成房屋
     *
     * @param
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public int buildHouse(List<BaseCellInfo> list, String sortType, String site, BaseBuildInfo baseBuildInfo) {
        int num = NumberEnum.ONE.getNum();
        List<BaseHouseInfo> maxHouseNos = null;
        //如果排序类型为按层组合  针对首次维护的自然幢
        if (NumStrEnum.ONE.getNum().equals(sortType)) {
            //根据房屋性质、单元编号查询该楼层最大的房间名
            maxHouseNos = baseHouseInfoMapper.getMaxHouseNoByBuildNo(baseBuildInfo.getId());
        }
        int cellNo = 0;
        int houseNo = 1;
        List<BaseHouseInfo> houses = new ArrayList<>();
        List<BaseCellInfo> newList = list.stream().sorted(Comparator.comparing(BaseCellInfo::getCellType)).collect(Collectors.toList());
        int aa = 1;
        for (int k = 0; k < newList.size(); k++) {
            //更新已有房间名
            //是否可以查询当前楼层最大房间号标记
            BaseCellInfo baseCellInfo = newList.get(k);
            //如果排序类型为按层组合  针对首次维护的自然幢
            if (NumStrEnum.ONE.getNum().equals(sortType)) {
                //房屋性质判断是重新生成房间编号  房屋性质不同则对房间编号重新生成
                if (k > 0) {
                    if (!baseCellInfo.getCellType().equals(newList.get(k - 1).getCellType())) {
                        houseNo = 1;
                        aa = 1;
                    }
                }
            }
            cellNo = getCellNo(baseCellInfo.getBuildNo(), cellNo);
            //查询是否已有房屋,有房屋为二次维护，则不进行房屋新增操作,只修改单元信息
            int countByCellNo = baseHouseInfoMapper.getHouseCountByCellNo(baseCellInfo.getId());
            if (countByCellNo > 0) {
                //修改单元时同步修改房间编号
                int update = baseCellInfoMapper.update(baseCellInfo);
                if (update > 0) {
                    List<BaseHouseInfo> listByCellNo = baseHouseInfoMapper.getListByCellNo(baseCellInfo.getId());
                    listByCellNo.forEach(h -> h.setHouseSite(site + baseCellInfo.getCellName() + h.getRoomName()));
                    baseHouseInfoMapper.updateListByHouseId(listByCellNo);
                }
                continue;
            }
            String houseSite = site + baseCellInfo.getCellName();
            //操作单元
            BaseCellInfo info = buildCell(baseCellInfo, cellNo);
            //不需要操作房屋  执行下一次循环
            if (null == info) {
                continue;
            }
            String roomName = null;
            BaseHouseInfo baseHouseInfo;
            int startFloor = Integer.parseInt(baseCellInfo.getStartFloor());
            int endFloor = Integer.parseInt(baseCellInfo.getEndFloor());
            int houseNum = Integer.parseInt(baseCellInfo.getHouseNum());
            int roomNo = 1;
            for (int j = 1; j <= houseNum; j++) {
                for (int i = startFloor; i <= endFloor; i++) {
                    //0层时不执行操作
                    if (NumberEnum.ZERO.getNum() == i) {
                        continue;
                    }
                    //如果排序类型为按层组合  针对非首次维护的自然幢
                    if (NumStrEnum.ONE.getNum().equals(sortType)) {
                        for (BaseHouseInfo h : maxHouseNos) {
                            if (String.valueOf(i).equals(h.getFloorNo()) && baseCellInfo.getCellType().equals(h.getHouseUse())) {
                                houseNo = aa + h.getHouseNo();
                                continue;
                            }
                        }
                    }
                    //组合方式  0单元  1层
                    switch (sortType) {
                        case "0":
                            roomName = String.valueOf(i) + String.format("%02d", j);
                            break;
                        case "1":
                            roomName = String.valueOf(i) + String.format("%02d", houseNo);
                            break;
                    }
                    baseHouseInfo = new BaseHouseInfo();
                    baseHouseInfo.setId(UUIDUtil.getUUID());
                    baseHouseInfo.setHouseSite(houseSite + roomName);
                    baseHouseInfo.setRoomName(roomName);
                    baseHouseInfo.setRoomNo(String.format("%03d", roomNo));
                    baseHouseInfo.setBuildNo(baseCellInfo.getBuildNo());
                    baseHouseInfo.setCellNo(baseCellInfo.getId());
                    baseHouseInfo.setFloorNo(String.valueOf(i));
                    baseHouseInfo.setHouseUse(baseCellInfo.getCellType());
                    baseHouseInfo.setBankCode(baseBuildInfo.getBankCode());
                    baseHouseInfo.setFirstMode(baseBuildInfo.getFirstMode());
                    baseHouseInfo.setPrice(BigDecimal.ZERO);
                    houses.add(baseHouseInfo);
                }
                houseNo++;
                roomNo++;
                aa++;
            }
        }
        if (houses.size() > 0) {
            baseHouseInfoMapper.insertHouseInfoList(houses);
        }
        return num;
    }

    @Override
    public List<BaseCellInfo> getList(BaseCellInfo baseCellInfo) {
        return baseCellInfoMapper.getList(baseCellInfo);
    }


    @Override
    public PageInfo<BaseCellInfo> getAllList(Page page, BaseCellInfo baseCellInfo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseCellInfo> list = baseCellInfoMapper.getList(baseCellInfo);
        PageInfo<BaseCellInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public List<Map<String, String>> getCellListByBuildNo(String buildNo) {
        return baseCellInfoMapper.getCellListByBuildNo(buildNo);
    }


    @Override
    public CommonResult insert(BaseCellInfo baseCellInfo) {
        return null;
    }

    @Override
    public CommonResult update(BaseCellInfo baseCellInfo) {
        return null;
    }

    @Override
    public CommonResult delete(String id) {
        //查询是否有房间
        int num = baseHouseInfoMapper.getHouseCountByCellNo(id);
        int i = 0;
        if (num > 0) {
            return CommonResult.strResult(NumberEnum.ZERO.getNum(), "已存在房间，请先删除房间信息！");
        }
        //删除单元表
        num = baseHouseInfoMapper.selectByCellNoDel(id);
        if (num == 0) {
            num = baseModifyDetailMapper.selectByBusiId(id);
            if (num == 0) {
                i = baseCellInfoMapper.delete(id);
            } else {
                i = baseCellInfoMapper.updateState(id);
            }
        } else {
            i = baseCellInfoMapper.updateState(id);
        }
        return CommonResult.ResponseResult(i);
    }

    @Override
    public PageInfo<BaseCellInfo> getList(Page page, BaseCellInfo baseCellInfo) {
        return null;
    }

    @Override
    public BaseCellInfo getInfo(String id) {
        return baseCellInfoMapper.getInfo(id);
    }

    /**
     * 单元
     *
     * @param buildNo
     * @return
     */
    @Override
    public List<BaseCellInfoList> getListInfo(String buildNo) {
        int num = baseModifyReqMapper.selectCountByBusinessIdNotFlow(buildNo);
        List<BaseCellInfoList> baseCellInfoLists = new ArrayList<>();
        List<BaseCellInfo> cellTypes = baseCellInfoMapper.selectCellType(buildNo);
        if (cellTypes.size() == 0) {
            return null;
        }
        //查询是地下室还是住宅
        for (int i = 0; i < cellTypes.size(); i++) {
            List<BaseCellInfo> baseCellInfos = baseCellInfoMapper.getInfoList(cellTypes.get(i).getCellType(), buildNo);
            BaseCellInfoList baseCellInfoList = new BaseCellInfoList();
            //添加该类的列表
            for (BaseCellInfo baseCellInfo : baseCellInfos) {
                BaseCellInfo b = baseCellInfoMapper.selectMaxByCellNo(baseCellInfo.getId());
                if (b == null) {
                    baseCellInfo.setNum(num);
                    baseCellInfo.setMaxFloor("0");
                    baseCellInfo.setMinFloor("0");
                    baseCellInfo.setMaxRoomNo("0");
                } else {
                    baseCellInfo.setNum(num);
                    baseCellInfo.setMaxFloor(b.getMaxFloor());
                    baseCellInfo.setMinFloor(b.getMinFloor());
                    baseCellInfo.setMaxRoomNo(b.getMaxRoomNo());
                }
            }
            baseCellInfoList.setType(cellTypes.get(i).getCellType());
            baseCellInfoList.setTypeNo(cellTypes.get(i).getCellTypeNo());
            baseCellInfoList.setBaseCellInfos(baseCellInfos);
            baseCellInfoLists.add(i, baseCellInfoList);
        }
        return baseCellInfoLists;
    }

    /**
     * 单元变更
     *
     * @param baseCellInfos
     * @return
     */
    @Override
    @Transactional
    public CommonResult updateToSave(List<BaseCellInfo> baseCellInfos) throws Exception {
        String uuid = "";
        int no = 0;
       String buildNo= baseCellInfos.get(0).getBuildNo();
       if (("1").equals(baseCellInfos.get(0).getFuzzy())){
           baseCellInfos.remove(0);
       }
        for (BaseCellInfo b : baseCellInfos) {
            if (StringUtils.isNotBlank(b.getRId())) {
                baseModifyDetailMapper.delByReqNo(b.getRId());
                baseModifyReqMapper.dele(b.getRId());
                break;
            }
        }
        //查询该自然幢下的所有单元
        List<BaseCellInfo> oldBaseCellInfos = baseCellInfoMapper.getAllListByBuildToTransform(buildNo);
        //获取旧值的id集合
        List<String> oldCellId = new ArrayList<>();
        for (BaseCellInfo b : oldBaseCellInfos) {
            oldCellId.add(b.getId());
        }
        List<String> newCellId = new ArrayList<>();
        for (BaseCellInfo b : baseCellInfos) {
            newCellId.add(b.getId());
        }
        uuid = UUIDUtil.getUUID();
        //查询修改的数据
        for (int i = 0; i < baseCellInfos.size(); i++) {
            if (null != oldCellId && baseCellInfos.size() != 0) {
                if (oldCellId.contains(baseCellInfos.get(i).getId())) {
                    BaseCellInfo baseCellInfo = baseCellInfoMapper.getInfo(baseCellInfos.get(i).getId());
                    //updateToSave(T oldObject, T newObject, String businessId, String modifyType, String modifyCause, String uuid)
                    baseCellInfos.get(i).setRId(null);
                    baseCellInfo.setMaxRoomNo(baseCellInfos.get(i).getMaxRoomNo());
                    baseCellInfo.setMaxFloor(baseCellInfos.get(i).getMaxFloor());
                    baseCellInfo.setMinFloor(baseCellInfos.get(i).getMinFloor());
                    baseCellInfo.setCellTypeNo(baseCellInfos.get(i).getCellTypeNo());
                    no = modifyUtil.updateToSave(baseCellInfo, baseCellInfos.get(i), baseCellInfo.getBuildNo(), "base_cell_info_update", null, uuid);
                    if (no <= 0) {
                        continue;
                    }
                    Iterator<String> itr = oldCellId.iterator();
                    while (itr.hasNext()) {
                        if (itr.next().contains(newCellId.get(i))) {
                            itr.remove();
                        }
                    }
                }//新增
                else if (StringUtils.isBlank(baseCellInfos.get(i).getId()) || null == baseCellInfoMapper.getInfo(baseCellInfos.get(i).getId())) {
                    no = addCell(baseCellInfos.get(i), uuid);
                }
            }
        }//删除
        if (oldCellId.size() != 0) {
            List<BaseModifyDetail> baseModifyDetails = new ArrayList<>();
            BaseCellInfo oldBase = new BaseCellInfo();
            for (String oldCell : oldCellId) {
                for (BaseCellInfo b : oldBaseCellInfos) {
                    if (b.getId().equals(oldCell)) {
                        oldBase = b;
                        List<BaseHouseInfo> listss=   baseHouseInfoMapper.selectByCellNo(b.getId());
                        if (!listss.isEmpty()){
                            throw new CourseException(ShiroResultEnum.FAIL.getCode(), b.getCellName()+"有房屋无法删除");
                        }
                    }
                }
                BaseCellInfo baseCellInfo = baseCellInfoMapper.getInfo(oldCell);
                String cellId = baseCellInfo.getId();
                baseModifyDetails.add(addBaseModifyCell(cellId, uuid, cellId, "id", "单元id"));
                baseModifyDetails.add(addBaseModifyCell(baseCellInfo.getCellName(), uuid, cellId, "cellName", "单元名称"));
                baseModifyDetails.add(addBaseModifyCell(baseCellInfo.getStartFloor(), uuid, cellId, "startFloor", "开始楼层"));
                baseModifyDetails.add(addBaseModifyCell(baseCellInfo.getEndFloor(), uuid, cellId, "endFloor", "结束楼层"));
                baseModifyDetails.add(addBaseModifyCell(baseCellInfo.getElevator(), uuid, cellId, "elevator", "是否有电梯"));
                baseModifyDetails.add(addBaseModifyCell(baseCellInfo.getHouseNum(), uuid, cellId, "houseNum", "房屋户数"));
                baseModifyDetails.add(addBaseModifyCell(baseCellInfo.getCellType(), uuid, cellId, "cellType", "结构类型"));
                baseModifyDetails.add(addBaseModifyCell(baseCellInfo.getBuildNo(), uuid, cellId, "buildNo", "自然幢id"));
                List<BaseHouseInfo> list = baseHouseInfoMapper.selectAllByCell(oldCell);
                if (list == null || list.size() == 0) {
                    no = 1;
                } else {
                    String id = list.get(0).getCellNo();
                    for (BaseHouseInfo b : list) {
                        //状态改为代销户
                        baseHouseInfoMapper.updateStateById(b.getId(), NumStrEnum.THREE.getNum());
                        if (null == b.getStruArea()) {
                            b.setStruArea(BigDecimal.ZERO);
                        }
                        String ids = b.getId();
                        baseModifyDetails.add(addBaseModify(b.getHouseSite(), uuid, id, "houseSite", "房屋地址", ids, 0));
                        baseModifyDetails.add(addBaseModify(b.getHouseAttr(), uuid, id, "houseAttr", "房屋结构", ids, 0));
                        baseModifyDetails.add(addBaseModify(b.getHouseUse(), uuid, id, "houseUse", "房屋性质", ids, 0));
                        baseModifyDetails.add(addBaseModify(b.getStruArea().toString(), uuid, id, "struArea", "面积", ids, 0));
                        baseModifyDetails.add(addBaseModify(b.getRoomName(), uuid, id, "roomName", "房间名称", ids, 0));
                        baseModifyDetails.add(addBaseModify(b.getFirstMode(), uuid, id, "firstMode", "初交模式", ids, 0));
                    }
                }
                no = baseModifyDetailMapper.insertList(baseModifyDetails);
                if (no == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "操作失败");
                }
            }
        }
        int changeDetail = baseModifyDetailMapper.selectByReq(uuid);
        if (changeDetail != 0) {
            no = modifyUtil.saveModifyReqCell(uuid, baseCellInfos.get(0).getBuildNo(), "base_cell_info_update", null);
            List<String> list = baseModifyDetailMapper.selectCellById(uuid);
        } else {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该单元没有变更数据请重新变更");
        }
        return new CommonResult(no, "操作成功", uuid);
    }

    /**
     * 房屋结构变更分页
     *
     * @param page
     * @param baseCellInfo
     * @return
     */
    @Override
    public PageInfo<BaseCellInfo> getAllListAndDetail(Page page, BaseCellInfo baseCellInfo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        if (StringUtils.isNotBlank(baseCellInfo.getReqNo())) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该自然幢正在变更");
        }
        List<BaseCellInfo> list = baseCellInfoMapper.getListAndReq(baseCellInfo);
        for (BaseCellInfo b : list) {
            int num = baseModifyDetailMapper.selectChangeHouseByCell(b.getId());
            b.setNum(num);
        }
        PageInfo<BaseCellInfo> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    /**
     * 结构变更新增
     */
    private int addCell(BaseCellInfo baseCellInfo, String uuid) {
        int no = 0;
        String id = UUIDUtil.getUUID();
        List<BaseModifyDetail> baseModifyDetails = new ArrayList<>();
        BaseModifyDetail baseModifyDetail = new BaseModifyDetail();
        baseModifyDetail.setNewValue(baseCellInfo.getStartFloor());
        baseModifyDetail.setReqNo(uuid);
        baseModifyDetail.setType(NumStrEnum.ZERO.getNum());
        baseModifyDetail.setBusinessId(id);
        baseModifyDetail.setColumnName("startFloor");
        baseModifyDetail.setName("开始楼层");
        baseModifyDetails.add(baseModifyDetail);
        BaseModifyDetail b = new BaseModifyDetail();
        b.setNewValue(baseCellInfo.getEndFloor());
        b.setReqNo(uuid);
        b.setType(NumStrEnum.ZERO.getNum());
        b.setBusinessId(id);
        b.setColumnName("endFloor");
        b.setName("结束楼层");
        baseModifyDetails.add(b);
        //3
        BaseModifyDetail ba = new BaseModifyDetail();
        ba.setNewValue(baseCellInfo.getHouseNum());
        ba.setReqNo(uuid);
        ba.setType(NumStrEnum.ZERO.getNum());
        ba.setBusinessId(id);
        ba.setColumnName("houseNum");
        ba.setName("每层房屋数量");
        baseModifyDetails.add(ba);
        BaseModifyDetail base3 = new BaseModifyDetail();
        base3.setNewValue(id);
        base3.setReqNo(uuid);
        base3.setType(NumStrEnum.ZERO.getNum());
        base3.setBusinessId(id);
        base3.setColumnName("id");
        base3.setName("单元id");
        baseModifyDetails.add(base3);
        BaseModifyDetail bas = new BaseModifyDetail();
        Integer c = 0;
        if (StringUtils.isBlank(baseCellInfo.getCellNo())) {
            String cell = baseCellInfoMapper.selectCellNo(baseCellInfo.getBuildNo());
            c = Integer.parseInt(cell) + 1;
        } else {
            c = Integer.parseInt(baseCellInfo.getCellNo());
        }

        String cell = String.format("%4d", c).replace(" ", NumStrEnum.ZERO.getNum());
        bas.setNewValue(cell);
        bas.setReqNo(uuid);
        bas.setType(NumStrEnum.ZERO.getNum());
        bas.setBusinessId(id);
        bas.setColumnName("cellNo");
        bas.setName("单元号");
        baseModifyDetails.add(bas);
        BaseModifyDetail base = new BaseModifyDetail();
        base.setNewValue(baseCellInfo.getBuildNo());
        base.setReqNo(uuid);
        base.setType(NumStrEnum.ZERO.getNum());
        base.setBusinessId(id);
        base.setColumnName("buildNo");
        base.setName("自然幢id");
        baseModifyDetails.add(base);
        BaseModifyDetail base1 = new BaseModifyDetail();
        base1.setNewValue(baseCellInfo.getElevator());
        base1.setReqNo(uuid);
        base1.setType(NumStrEnum.ZERO.getNum());
        base1.setBusinessId(id);
        base1.setColumnName("elevator");
        base1.setName("是否有电梯");
        baseModifyDetails.add(base1);
        BaseModifyDetail base2 = new BaseModifyDetail();
        base2.setNewValue(baseCellInfo.getCellType());
        base2.setReqNo(uuid);
        base2.setType(NumStrEnum.ZERO.getNum());
        base2.setBusinessId(id);
        base2.setColumnName("cellType");
        base2.setName("结构类型");
        baseModifyDetails.add(base2);
        BaseModifyDetail base4 = new BaseModifyDetail();
        base4.setNewValue(baseCellInfo.getCellName());
        base4.setReqNo(uuid);
        base4.setType(NumStrEnum.ZERO.getNum());
        base4.setBusinessId(id);
        base4.setColumnName("cellName");
        base4.setName("单元名称");
        baseModifyDetails.add(base4);
        int endFloor = Integer.parseInt(baseCellInfo.getEndFloor());
        int startFloor = Integer.parseInt(baseCellInfo.getStartFloor());
        int houseNum = Integer.parseInt(baseCellInfo.getHouseNum());
        if (endFloor > 0 && startFloor < 0 || endFloor < 0 && startFloor > 0) {
            no = Math.abs(endFloor - startFloor);
        } else {
            no = Math.abs(endFloor - startFloor) + 1;
        }
        for (int j = 0; j < no; j++) {
            if (startFloor + j == 0) {
                startFloor = startFloor + 1;
            }
            for (int q = 0; q < houseNum; q++) {
                if (startFloor + j == 0) {
                    continue;
                }
                String room = String.format("%3d", q + 1).replace(" ", NumStrEnum.ZERO.getNum());

                String roomName = startFloor + j + room.substring(1);
                String subRegionName = "";
                //获取地址
                BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfoById(baseCellInfo.getBuildNo());
                if (null != baseBuildInfo && null != baseBuildInfo.getSubRegionNo()) {
                    BaseSubRegionInfo info = baseSubRegionInfoMapper.getInfo(baseBuildInfo.getSubRegionNo());
                    if (null != info && null != info.getSubRegionName()) {
                        subRegionName = info.getSubRegionName();
                    }
                }
                BaseRegionInfo baseRegionInfo = baseRegionInfoMapper.getInfo(baseBuildInfo.getRegionNo());
                String zoneName = zoneCodeMapper.getZoneName(StringUtils.substring(baseRegionInfo.getZoneCode(), 0, 6));
                String houseSite = zoneName + baseRegionInfo.getRegionName() + subRegionName + baseBuildInfo.getBuildName() + baseCellInfo.getCellName() + roomName;
                String ids = UUIDUtil.getUUID();
                baseModifyDetails.add(addBaseModify(ids, uuid, id, "id", "房屋id", ids, 1));
                baseModifyDetails.add(addBaseModify(houseSite, uuid, id, "houseSite", "房屋地址", ids, 1));
                baseModifyDetails.add(addBaseModify(startFloor + j + "", uuid, id, "floorNo", "层数", ids, 1));
                baseModifyDetails.add(addBaseModify(room, uuid, id, "roomNo", "房间号", ids, 1));
                baseModifyDetails.add(addBaseModify(null, uuid, id, "houseAttr", "房屋结构", ids, 1));
                baseModifyDetails.add(addBaseModify(baseCellInfo.getCellType(), uuid, id, "houseUse", "房屋性质", ids, 1));
                baseModifyDetails.add(addBaseModify(null, uuid, id, "struArea", "面积", ids, 1));
                baseModifyDetails.add(addBaseModify(baseCellInfo.getBuildNo(), uuid, id, "buildNo", "自然幢id", ids, 1));
                baseModifyDetails.add(addBaseModify(id, uuid, id, "cellNo", "单元id", ids, 1));
                baseModifyDetails.add(addBaseModify(baseBuildInfo.getBankCode(), uuid, id, "bankCode", "承办银行", ids, 1));
                baseModifyDetails.add(addBaseModify(roomName, uuid, id, "roomName", "房间名称", ids, 1));
                baseModifyDetails.add(addBaseModify(NumStrEnum.ZERO.getNum(), uuid, id, "state", "状态", ids, 1));
                baseModifyDetails.add(addBaseModify(null, uuid, id, "firstMode", "初交模式", ids, 1));
                baseModifyDetails.add(addBaseModify(NumStrEnum.FOUR.getNum(), uuid, id, "dueState", "缴存状态", ids, 1));
                baseModifyDetails.add(addBaseModify(NumStrEnum.ZERO.getNum(), uuid, id, "flowInProgress", "在途状态", ids, 1));
                baseModifyDetails.add(addBaseModify(NumStrEnum.ZERO.getNum(), uuid, id, "ownerState", "是否有业主", ids, 1));
                baseModifyDetails.add(addBaseModify(NumStrEnum.ZERO.getNum(), uuid, id, "isAffiliated", "是否主房", ids, 1));
                baseModifyDetails.add(addBaseModify(NumStrEnum.ZERO.getNum(), uuid, id, "price", "价格", ids, 1));
            }
        }
        baseModifyDetailMapper.insertList(baseModifyDetails);
        if (no == 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "操作失败");
        }
        return no;
    }

    /**
     * 添加modify
     */
    public BaseModifyDetail addBaseModify(String newValue, String uuid, String id, String columnName, String name, String businessNextId, int type) {
        BaseModifyDetail base = new BaseModifyDetail();
        if (type == 0) {
            base.setOldValue(newValue);
        } else {
            base.setNewValue(newValue);
        }

        base.setReqNo(uuid);
        base.setType(NumStrEnum.ONE.getNum());
        base.setBusinessId(id);
        base.setCreater(ShiroUserUtil.getUserName());
        base.setBusinessNextId(businessNextId);
        base.setColumnName(columnName);
        base.setName(name);
        return base;
    }


    /**
     * 添加modify 单元
     */
    private BaseModifyDetail addBaseModifyCell(String newValue, String uuid, String id, String columnName, String name) {
        BaseModifyDetail base = new BaseModifyDetail();
        base.setOldValue(newValue);
        base.setReqNo(uuid);
        base.setType(NumStrEnum.ZERO.getNum());
        base.setBusinessId(id);
        base.setCreater(ShiroUserUtil.getUserName());
        base.setColumnName(columnName);
        base.setName(name);
        return base;
    }

    /**
     * 单元变更
     *
     * @param buildNo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<BaseCellInfoList> getListInfoUpdate(String buildNo, String reqNo) {
        List<BaseCellInfoList> baseCellInfoEnd = new ArrayList<>();
        //如果没有变更
        if (StringUtils.isBlank(reqNo)) {
            List<BaseCellInfoList> oldBaseCellInfo = baseCellInfoService.getListInfo(buildNo);
            if (null == oldBaseCellInfo) {
                return null;
            }
            for (BaseCellInfoList b : oldBaseCellInfo) {
                List<BaseCellInfo> oldBase = b.getBaseCellInfos();
                for (BaseCellInfo ba : oldBase) {
                    //查询最大的缴存层数  最小的缴存层数  最小的房屋号
                    int expMinFloor = 0;
                    int expMaxFloor = 0;
                    int expRoom = 0;
                    BaseCellInfo base = baseHouseInfoMapper.selectAstrictFloor(ba.getId());
                    String allHouse = baseHouseInfoMapper.selectByCellNoId(ba.getId());
                    BaseCellInfo baseCellInfo = expProjectReqDetailMapper.selectByHouseAndExp(allHouse);
                    if (null != baseCellInfo) {
                        expMinFloor = Integer.parseInt(baseCellInfo.getMinFloor());
                        expMaxFloor = Integer.parseInt(baseCellInfo.getMaxFloor());
                        if (!baseCellInfo.getMaxRoomNo().equals(NumStrEnum.ZERO.getNum())) {
                            expRoom = Integer.parseInt(baseCellInfo.getMaxRoomNo().replaceAll("^(0+)", ""));
                        }
                    }
                    int houseMinFloor = Integer.parseInt(base.getMinFloor());
                    int houseMaxFloor = Integer.parseInt(base.getMaxFloor());
                    if (houseMinFloor > expMinFloor) {
                        ba.setMinFloor(houseMinFloor + "");
                    } else {
                        ba.setMinFloor(expMinFloor + "");
                    }
                    if (houseMaxFloor > expMaxFloor) {
                        ba.setMaxFloor(houseMaxFloor + "");
                    } else {
                        ba.setMaxFloor(expMaxFloor + "");
                    }
                    int houseRoom = 0;

                    if (!base.getMaxRoomNo().equals(NumStrEnum.ZERO.getNum())) {
                        houseRoom = Integer.parseInt(base.getMaxRoomNo().replaceAll("^(0+)", ""));
                    }

                    if (houseRoom > expRoom) {
                        ba.setMaxRoomNo(houseRoom + "");
                    } else {
                        ba.setMaxRoomNo(expRoom + "");
                    }

                }
            }
            return oldBaseCellInfo;
        } else {
            //如果有变更
            //通过单元类型的分组
            List<BaseCellInfo> list = baseCellInfoMapper.selectCellIdByType(buildNo);
            //列转行名称
            List<String> li = baseModifyDetailMapper.getColumnListAndCell(reqNo);
            //查看该类型的单元id
            //查询这个单元删除
            List<String> outList = baseModifyDetailMapper.selectDeletesCellId(reqNo);
            //查询这个单元添加id
            List<String> addList = baseModifyDetailMapper.selectAddCellId(reqNo);
            //查询这个单元添加
            List<BaseCellInfo> baseCellInfoAdd = new ArrayList<>();
            if (0 != addList.size()) {
                for (String addCellId : addList) {
                    Map map = new HashMap();
                    map.put("list", li);
                    map.put("reqNo", reqNo);
                    map.put("id", addCellId);
                    BaseCellInfo cellList = baseModifyDetailMapper.selectAddCell(map);
                    baseCellInfoAdd.add(cellList);
                }
            }
            //删除
            if (0 != outList.size()) {
                Iterator<BaseCellInfo> itr = list.iterator();
                while (itr.hasNext()) {
                    List<String> idList= new ArrayList<>();
                    BaseCellInfo next = itr.next();
                    String[] ids = next.getId().split(",");
                    for (String id : ids) {
                        if (outList.contains(id)) {
                            if (ids.length == 1) {
                                itr.remove();
                            }
                        }else {
                            idList.add(id);
                        }
                    }
                    String join = String.join(",", idList);
                    next.setId(join);
                }
//                for (int i = 0; i < list.size(); i++) {
//                    List<String> idList= new ArrayList<>();
//                    BaseCellInfo baseCellInfo = list.get(i);
//                    String[] ids = baseCellInfo.getId().split(",");
//                    for (String id : ids) {
//                        Iterator<BaseCellInfo> itr = list.iterator();
//                        while (itr.hasNext()) {
//                            BaseCellInfo next = itr.next();
//                            //若这单元类型只有一个单元并且被删除则没有该类型
//                            if (outList.contains(id)) {
//                                if (ids.length == 1) {
//                                    itr.remove();
//                                }
//                            }else {
//                                idList.add(id);
//                            }
//                        }
//                    }
//                    String join = String.join(",", idList);
//                    baseCellInfo.setId(join);
//                }
            }
            //所有的有效单元分类及单元id
            List<BaseCellInfo> cellInfos = CellTypeList(list, baseCellInfoAdd);
            if (0 != cellInfos.size()) {
                for (BaseCellInfo b : cellInfos) {
                    List<BaseCellInfo> baseCellInfos = new ArrayList<>();
                    String[] ids = b.getCellType().split(",");
                    for (String id : ids) {
                        BaseCellInfo baseCellInfo;
                        baseCellInfo = baseCellInfoMapper.getInfo(id);
                        if (null == baseCellInfo) {
                            Map map = new HashMap();
                            map.put("list", li);
                            map.put("reqNo", reqNo);
                            map.put("id", id);
                            baseCellInfo = baseModifyDetailMapper.selectAddCell(map);
                        } else {
                            int n = baseModifyDetailMapper.selectCountChangeCell(reqNo, id);
                            if (n != 0) {
                                baseCellInfo = modifyUtil.getCompleteEntityCell(reqNo, baseCellInfo, id);
                            }
                        }
                        //查询最大缴存层数  最小缴存层数  最小房间号
                        BaseCellInfo base = new BaseCellInfo();
                        if (StringUtils.isNotBlank(baseCellInfo.getId())) {
                            base = baseHouseInfoMapper.selectAstrictFloor(baseCellInfo.getId());
                            baseCellInfo.setMinFloor(base.getMinFloor());
                            baseCellInfo.setMaxFloor(base.getMaxFloor());
                            String room = NumStrEnum.ZERO.getNum();
                            if (!base.getMaxRoomNo().equals(0)) {
                                room = base.getMaxRoomNo().replaceAll("^(0+)", "");
                            }
                            baseCellInfo.setMaxRoomNo(room);
                        }
                        baseCellInfos.add(baseCellInfo);
                    }
                    BaseCellInfoList baseCellInfoList = new BaseCellInfoList();
                    baseCellInfoList.setTypeNo(b.getId());
                    if (StringUtils.isBlank(b.getId())) {
                        throw new CourseException(ShiroResultEnum.FAIL.getCode(), "单元类型没有");
                    }
                    baseCellInfoList.setTypeNo(dicContentMapper.selectName(b.getId()));
                    baseCellInfoList.setType(b.getId());
                    baseCellInfoList.setBaseCellInfos(baseCellInfos);
                    baseCellInfoEnd.add(baseCellInfoList);
                }
            }
            for (BaseCellInfoList b : baseCellInfoEnd) {
                List<BaseCellInfo> base = b.getBaseCellInfos();
                Collections.sort(base);
            }
            return baseCellInfoEnd;
        }
    }

    /**
     * 结构类型
     *
     * @param all
     * @param add
     * @return
     */
    private List<BaseCellInfo> CellTypeList(List<BaseCellInfo> all, List<BaseCellInfo> add) {
        List<BaseCellInfo> list = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        if (null != add) {
            for (BaseCellInfo b : add) {
                all.add(b);
            }
        }
        for (BaseCellInfo b : all) {
            String id = b.getId();
            String cellType = b.getCellType();
            if (map.containsKey(b.getCellType())) {
                String ids = map.get(b.getCellType()) + "," + id;
                map.remove(b.getCellType());
                map.put(b.getCellType(), ids);
            } else {
                map.put(cellType, id);
            }
        }
        for (Map.Entry<String, String> mapAll : map.entrySet()) {
            BaseCellInfo baseCellInfo = new BaseCellInfo();
            baseCellInfo.setCellType(mapAll.getValue());
            baseCellInfo.setId(mapAll.getKey());
            list.add(baseCellInfo);
        }
        return list;
    }

}
